package com.wzs.handler;


import com.wzs.setting.domain.Author;
import com.wzs.setting.domain.Readr;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("判断是否执行过登录验证");

        String uri = request.getServletPath();
        if ("/index.html".equals(uri)){
            return true;
        }

        HttpSession session = request.getSession();
        Object user = session.getAttribute("SESSION_USER");

        if (user == null) {
            System.out.println("您不具备权限，请先登录");
            response.sendRedirect(request.getContextPath() + "/login-r.jsp");
            return false;
        }

        if (user instanceof Readr) {
            Readr user1 = (Readr) user;
            request.getSession().setAttribute("SESSION_USER", user1);
            System.out.println(user1.getName() + "处于登录状态，可以执行操作");
            return true;
        } else if (user instanceof Author) {
            Author user1 = (Author) user;
            request.getSession().setAttribute("SESSION_USER", user1);
            System.out.println(user1.getFullname() + "处于登录状态，可以执行操作");
            return true;
        } else {
            System.out.println("请先登录");
            response.sendRedirect(request.getContextPath() + "/index.html");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
